﻿using Juli.Mes.Customers.Dtos;
using Lion.AbpPro.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Users;
namespace Juli.Mes.Customers
{
    public class CustomerAppService : MesAppService, ICustomerAppService
    {
        private readonly IRepository<Customer> _customerRepository;
        private readonly IWebHostEnvironment _webHostEnv;

        private readonly ICurrentTenant _currentTenant;
        private readonly ICurrentUser _currentUser;

        public CustomerAppService(IRepository<Customer> customerRepository,
            IWebHostEnvironment webHostEnv,
            ICurrentTenant currentTenant,
            ICurrentUser currentUser)
        {
            _customerRepository = customerRepository;
            _webHostEnv = webHostEnv;
            _currentTenant = currentTenant;
            _currentUser = currentUser;
        }

        [HttpPost("create")]
        [SwaggerOperation("创建客户", Tags = new[] { "Customers" })]
        public async Task CreateCustomer(CustomerInputDto input)
        {
            var entity = new Customer();

            entity = ObjectMapper.Map<CustomerInputDto, Customer>(input);

            await _customerRepository.InsertAsync(entity);
        }

        [HttpPost("delete")]
        [SwaggerOperation("删除客户", Tags = new[] { "Customers" })]
        public async Task DeleteCustomer(IdInput input)
        {

            await _customerRepository.DeleteAsync(p => p.Id == input.Id);
        }

        [HttpPost("edit")]
        [SwaggerOperation("编辑客户", Tags = new[] { "Customers" })]
        public async Task EditCustomer(CustomerInputDto input)
        {
            var entity = await _customerRepository.GetAsync(p => p.Id == input.Id);
            ObjectMapper.Map(input, entity);
            await _customerRepository.UpdateAsync(entity);
        }

        [HttpPost("page")]
        [SwaggerOperation("分页查询客户", Tags = ["Customers"])]
        public async Task<PagedResultDto<CustomerOutputDto>> ListCustomer(PageCustomerInputDto input)
        {
            var tenantId = _currentTenant.Id;
            var currentUser = _currentUser;

            var customerQuery = await _customerRepository.GetQueryableAsync();

            var query = from p in customerQuery
                        select p;

            query = query.WhereIf(!string.IsNullOrEmpty(input.Filter),
                p => p.CustomerName.Contains(input.Filter) || p.Province.Contains(input.Filter)
                || p.City.Contains(input.Filter) || p.Location.Contains(input.Filter));

            var items = query
                .OrderBy(e => e.CreationTime)
                .PageBy(input.SkipCount, input.PageSize)
            .ToList();

            var finalItems = ObjectMapper.Map<List<Customer>, List<CustomerOutputDto>>(items);

            var count = query.Count();

            return new PagedResultDto<CustomerOutputDto>()
            {
                Items = finalItems,
                TotalCount = count,
            };
        }


        [HttpPost("china")]
        [SwaggerOperation("中国省市数据", Tags = ["Customers"])]
        public ChinaDataDto GetChinaData()
        {
            var returnValue = new ChinaDataDto();
            var provinceData = GetLocalProvinceData();
            var cityData = GetLocalCityData();

            var provinceList = new List<dynamic>();
            var cityDic = new Dictionary<string, List<dynamic>>();

            foreach (var province in provinceData)
            {
                var cityList = new List<dynamic>();
                var provinceId = province["id"].ToString();
                var provinceName = province["name"].ToString();

                //    string pyName = GetPinYin(provinceName); 拼音 山西陕西会冲突
                var provinceDto = new
                {
                    Id = provinceName,
                    Label = provinceName,
                    Key = provinceName,
                    Value = provinceName,
                };

                var targetCityData = cityData[provinceId];

                provinceList.Add(provinceDto);

                foreach (var city in targetCityData)
                {
                    var cityId = city["id"].ToString();
                    var cityName = city["name"].ToString();

                    var cityDto = new
                    {
                        Label = cityName,
                        Key = cityName,
                        Value = cityName,
                    };

                    cityList.Add(cityDto);
                }

                cityDic.Add(provinceName, cityList);
            }

            returnValue.CityData = cityDic;
            returnValue.ProvinceData = provinceList;

            return returnValue;
        }
 
        private dynamic GetLocalProvinceData()
        {
            var wwwrootDir = Path.Combine(_webHostEnv.ContentRootPath, "wwwroot");
            var provinceJson = Path.Combine(wwwrootDir, "chinaJson", "province.json");
            string jsonContent = File.ReadAllText(provinceJson);
            var obj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
            return obj;
        }

        private dynamic GetLocalCityData()
        {
            var wwwrootDir = Path.Combine(_webHostEnv.ContentRootPath, "wwwroot");
            var cityJson = Path.Combine(wwwrootDir, "chinaJson", "city.json");
            string jsonContent = File.ReadAllText(cityJson);
            var obj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
            return obj;
        }
    }
}